package com.zhy.http.okhttp;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.inter.BasicsActivityInter;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.net.SocketTimeoutException;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by HOHO on 2017/4/25.
 */

public abstract class HttpArrayCallback<T> extends Callback<String> {
    private Context context;
    private boolean closeProgress = true;
    public String response;

    public HttpArrayCallback(Context context) {
        this.context = context;
    }

    @Override
    public String parseNetworkResponse(Response response, int id) throws Exception {
        Log.e(Constant.TAG, response.request().url().toString());
        return response.body().string();
    }

    @Override
    public void onError(Call call, Exception e, int id) {
        String error = "";
        if (e instanceof SocketTimeoutException) {
            error = context.getString(R.string.string9000);
        }
        if (e instanceof IOException) {
            error = context.getString(R.string.string9001);
        }
        Toast.makeText(context, error, Toast.LENGTH_SHORT).show();
        onFail(500, error);
    }

    @Override
    public void onResponse(String response, int id) {
        this.response = response;
        Log.e(Constant.TAG, response);
        Gson gson = new GsonBuilder().serializeNulls().create();
        BaseBean baseBean = gson.fromJson(response, BaseBean.class);
        gson.toJson(baseBean);
        if (baseBean.getCode() == Constant.SUCCEED_CODE) {
            Class<T> entityClass = (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            T data = gson.fromJson(response, entityClass);
            gson.toJson(data);
            onSuccess(data);
            onResponse(response);
        } else if (baseBean.getCode() == Constant.OVERDUE_CODE) {
        } else {
            onFail(baseBean.getCode(), baseBean.getMsg());
        }
    }

    protected void onResponse(String data) {

    }

    protected abstract void onSuccess(T data);

    protected abstract void onFail(int code, String msg);
}
